#!/bin/zsh
set -eu

CONTENTS="${0:A:h:h}"
APP="${CONTENTS:h}"
RESOURCES="$CONTENTS/Resources"
PAYLOAD="$RESOURCES/Payload"
PATCHER="$PAYLOAD/ADOFAILoaderPatcher.exe"

show_error() {
  if [[ "${ADOFAI_LOADER_TEST:-0}" == "1" ]]; then
    print -ru2 -- "$1"
  else
    /usr/bin/osascript - "$1" <<'APPLESCRIPT'
on run argv
  display alert "ADOFAI Mod Loader" message (item 1 of argv) as critical buttons {"OK"} default button "OK"
end run
APPLESCRIPT
  fi
  exit 1
}

show_success() {
  if [[ "${ADOFAI_LOADER_TEST:-0}" == "1" ]]; then
    print -r -- "$1"
  else
    /usr/bin/osascript - "$1" <<'APPLESCRIPT'
on run argv
  display alert "ADOFAI Mod Loader" message (item 1 of argv) buttons {"OK"} default button "OK"
end run
APPLESCRIPT
  fi
}

choose_action() {
  if [[ -n "${ADOFAI_LOADER_ACTION:-}" ]]; then
    print -r -- "$ADOFAI_LOADER_ACTION"
    return
  fi

  local choice
  choice="$(/usr/bin/osascript <<'APPLESCRIPT' || true
display dialog "Install or update Unity Mod Manager for the Steam edition of A Dance of Fire and Ice. Restore Original disables the loader without deleting your Mods folder." with title "ADOFAI Mod Loader" buttons {"Cancel", "Restore Original", "Install / Update"} default button "Install / Update" cancel button "Cancel"
button returned of result
APPLESCRIPT
)"
  case "$choice" in
    "Install / Update") print -r -- "install" ;;
    "Restore Original") print -r -- "restore" ;;
    *) print -r -- "cancel" ;;
  esac
}

find_mono() {
  local candidate
  for candidate in \
    /Library/Frameworks/Mono.framework/Versions/Current/Commands/mono \
    /opt/homebrew/bin/mono \
    /usr/local/bin/mono; do
    if [[ -x "$candidate" ]]; then
      print -r -- "$candidate"
      return 0
    fi
  done
  return 1
}

find_game() {
  setopt local_options null_glob
  local candidate
  local -a candidates
  candidates=(
    "$HOME/Downloads/ADOFAI/SteamLibrary/steamapps/common/A Dance of Fire and Ice/ADanceOfFireAndIce.app"
    "$HOME/Library/Application Support/Steam/steamapps/common/A Dance of Fire and Ice/ADanceOfFireAndIce.app"
  )
  for candidate in "${candidates[@]}" /Volumes/*/SteamLibrary/steamapps/common/'A Dance of Fire and Ice'/ADanceOfFireAndIce.app; do
    if [[ -d "$candidate" ]]; then
      print -r -- "$candidate"
      return 0
    fi
  done
  return 1
}

/usr/bin/codesign --verify --deep --strict "$APP" >/dev/null 2>&1 || \
  show_error "The loader app was modified or damaged. Download the ZIP again from adofai.exterverz.com."
[[ -f "$RESOURCES/PAYLOAD-SHA256.txt" ]] || \
  show_error "The loader payload manifest is missing. Download the ZIP again."
(
  cd "$RESOURCES"
  /usr/bin/shasum -a 256 -c PAYLOAD-SHA256.txt >/dev/null
) || show_error "The loader payload was modified or damaged. Download the ZIP again from adofai.exterverz.com."

ACTION="$(choose_action)"
[[ "$ACTION" != "cancel" ]] || exit 0

MONO="$(find_mono || true)"
[[ -n "$MONO" ]] || show_error "Mono is required to run the Mac bootstrap patcher. Install the official Mono package from mono-project.com/download/stable, then open this app again."

GAME_APP="${ADOFAI_GAME_APP:-$(find_game || true)}"
if [[ -z "$GAME_APP" && "${ADOFAI_LOADER_TEST:-0}" != "1" ]]; then
  GAME_APP="$(/usr/bin/osascript <<'APPLESCRIPT' 2>/dev/null || true
POSIX path of (choose application with prompt "Choose A Dance of Fire and Ice")
APPLESCRIPT
)"
  GAME_APP="${GAME_APP%/}"
fi

[[ -d "$GAME_APP" ]] || show_error "A Dance of Fire and Ice was not found. Install the Steam edition, or choose ADanceOfFireAndIce.app when prompted."
if /usr/bin/pgrep -f '[A]DanceOfFireAndIce' >/dev/null 2>&1; then
  show_error "Quit A Dance of Fire and Ice before changing the mod loader."
fi

LOG="$(/usr/bin/mktemp -t adofai-mod-loader)"
trap '/bin/rm -f "$LOG"' EXIT
if ! "$MONO" "$PATCHER" "$ACTION" "$GAME_APP" "$PAYLOAD" >"$LOG" 2>&1; then
  DETAILS="$(/usr/bin/tail -n 12 "$LOG")"
  show_error "The $ACTION operation stopped without changing unsupported files.

$DETAILS"
fi

if [[ "$ACTION" == "install" ]]; then
  show_success "Unity Mod Manager and the ADOFAI bootstrap are installed. You can now run the ADOFAI Seethrough installer, then launch the game through Steam."
else
  show_success "The original ADOFAI assembly was restored. Your Mods folder remains available for a later reinstall."
fi
